package www.yingdi365.com.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.jude.easyrecyclerview.EasyRecyclerView;
import com.jude.easyrecyclerview.adapter.BaseViewHolder;
import com.jude.easyrecyclerview.adapter.RecyclerArrayAdapter;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.view.CropImageView;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.HttpHeaders;
import com.qiniu.android.common.FixedZone;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.Configuration;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;

import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;

import okhttp3.Call;
import okhttp3.Response;
import www.yingdi365.com.R;
import www.yingdi365.com.base.ZjbBaseActivity;
import www.yingdi365.com.constant.Constant;
import www.yingdi365.com.model.AppQiniuToken;
import www.yingdi365.com.model.AppUser;
import www.yingdi365.com.model.AppUserModification;
import www.yingdi365.com.model.NormalBack;
import www.yingdi365.com.model.OkObject;
import www.yingdi365.com.model.QiNiu;
import www.yingdi365.com.util.GsonUtils;
import www.yingdi365.com.util.LogUtil;
import www.yingdi365.com.util.PicassoImageLoader;
import www.yingdi365.com.viewholder.SheZhiViewHolder;

public class SheZhiActivity extends ZjbBaseActivity implements View.OnClickListener {
    private RecyclerArrayAdapter<AppUser> adapter;
    private EasyRecyclerView recyclerView;
    private AppUser appUser;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_she_zhi);
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new PicassoImageLoader());   //设置图片加载器
        imagePicker.setShowCamera(true);  //显示拍照按钮
        imagePicker.setCrop(true);        //允许裁剪（单选才有效）
        imagePicker.setSaveRectangle(true); //是否按矩形区域保存
        imagePicker.setSelectLimit(9);    //选中数量限制
        imagePicker.setStyle(CropImageView.Style.RECTANGLE);  //裁剪框的形状
        imagePicker.setFocusWidth(500);   //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
        imagePicker.setFocusHeight(500);  //裁剪框的高度。单位像素（圆形自动取宽高最小值）
        imagePicker.setOutPutX(1000);//保存文件的宽度。单位像素
        imagePicker.setOutPutY(1000);//保存文件的高度。单位像素
        imagePicker.setMultiMode(false);
        init();
    }

    @Override
    protected void initSP() {

    }

    @Override
    protected void initIntent() {

    }

    @Override
    protected void findID() {
        recyclerView = (EasyRecyclerView) findViewById(R.id.recyclerView);
    }

    @Override
    protected void initViews() {
        initRecycle();
        ((TextView) findViewById(R.id.textViewTitle)).setText("设置");
    }

    @Override
    protected void setListeners() {
        findViewById(R.id.imageBack).setOnClickListener(this);
    }

    @Override
    protected void initData() {
        onRefresh();
    }

    private void initRecycle() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapterWithProgress(adapter = new RecyclerArrayAdapter<AppUser>(SheZhiActivity.this) {
            @Override
            public BaseViewHolder OnCreateViewHolder(ViewGroup parent, int viewType) {
                int layout = R.layout.view_shezhi;
                return new SheZhiViewHolder(parent, layout);
            }
        });
    }

    private OkObject getOkObject() {
        String url = Constant.HOST + Constant.Url.APPUSERSERVICE + "user";
        HttpHeaders headers = new HttpHeaders();
        headers.put(Constant.TOKEN, appLoginResult.getToken());
        LogUtil.LogShitou("WoFragment--getOkObject", appLoginResult.getToken());
        HashMap<String, String> params = new HashMap<>();
        return new OkObject(headers, params, url);
    }

    public void onRefresh() {
        OkObject okObject = getOkObject();
        OkGo.get(okObject.getUrl())//
                .tag(this)//
                .headers(okObject.getHeaders())
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        LogUtil.LogShitou("个人信息-设置", s);
                        try {
                            appUser = GsonUtils.parseJSON(s, AppUser.class);
                            adapter.add(appUser);
                            adapter.notifyDataSetChanged();
                        } catch (Exception e) {
                            showError(getResources().getString(R.string.shujuchucuo));
                        }
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                        showError(getResources().getString(R.string.wangluochucuo));
                    }

                    public void showError(String msg) {
                        View view_loaderror = LayoutInflater.from(SheZhiActivity.this).inflate(R.layout.view_loaderror, null);
                        TextView textMsg = (TextView) view_loaderror.findViewById(R.id.textMsg);
                        textMsg.setText(msg);
                        view_loaderror.findViewById(R.id.buttonReLoad).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                initData();
                            }
                        });
                        recyclerView.setErrorView(view_loaderror);
                        recyclerView.showError();
                    }
                });
    }

    private OkObject getOkObject1() {
        String url = Constant.HOST + Constant.Url.AppQiniuService + "st";
        HttpHeaders headers = new HttpHeaders();
        headers.put(Constant.TOKEN, appLoginResult.getToken());
        HashMap<String, String> params = new HashMap<>();
        return new OkObject(headers, params, url);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            if (data != null && requestCode == Constant.REQUEST_RESULT_CODE.IMAGE_PICKER) {
                final ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                showLoadingDialog();
                OkObject okObject = getOkObject1();
                OkGo.get(okObject.getUrl())//
                        .tag(this)//
                        .headers(okObject.getHeaders())
                        .execute(new StringCallback() {
                            @Override
                            public void onSuccess(String s, Call call, Response response) {
                                cancelLoadingDialog();
                                LogUtil.LogShitou("SheZhiActivity--onSuccess", "获取Qiniu上传访问授权信息" + s);
                                try {
                                    showLoadingDialog();
                                    final AppQiniuToken appQiniuToken = GsonUtils.parseJSON(s, AppQiniuToken.class);
                                    Configuration config = new Configuration.Builder()
                                            .chunkSize(512 * 1024)        // 分片上传时，每片的大小。 默认256K
                                            .putThreshhold(1024 * 1024)   // 启用分片上传阀值。默认512K
                                            .connectTimeout(10)           // 链接超时。默认10秒
                                            .useHttps(true)               // 是否使用https上传域名
                                            .responseTimeout(60)          // 服务器响应超时。默认60秒
                                            .zone(FixedZone.zone0)        // 设置区域，指定不同区域的上传域名、备用域名、备用IP。
                                            .build();

                                    // 重用uploadManager。一般地，只需要创建一个uploadManager对象
                                    UploadManager uploadManager = new UploadManager(config);
                                    String key = "touxiang" + System.currentTimeMillis() + ".png";
                                    String token = appQiniuToken.getUptoken();
                                    uploadManager.put(new File(images.get(0).path), key, token,
                                            new UpCompletionHandler() {
                                                @Override
                                                public void complete(String key, ResponseInfo info, JSONObject res) {
                                                    cancelLoadingDialog();
                                                    //res包含hash、key等信息，具体字段取决于上传策略的设置
                                                    if (info.isOK()) {
                                                        LogUtil.LogShitou("SheZhiActivity--complete", "成功");
                                                        LogUtil.LogShitou("SheZhiActivity--complete", "返回信息" + res.toString());
                                                        QiNiu qiNiu = GsonUtils.parseJSON(res.toString(), QiNiu.class);
                                                        String imgUrl = appQiniuToken.getUrl() + "/" + qiNiu.getKey();
                                                        appUser.setPhoto(imgUrl);
                                                        BaoCun();
                                                    } else {
                                                        LogUtil.LogShitou("SheZhiActivity--complete", "失败" + key);
                                                        LogUtil.LogShitou("SheZhiActivity--complete", "info  " + info.toString());
                                                    }
                                                }
                                            }, null);
                                } catch (Exception e) {
                                    Toast.makeText(SheZhiActivity.this, getResources().getString(R.string.shujuchucuo), Toast.LENGTH_SHORT).show();
                                }
                            }

                            @Override
                            public void onError(Call call, Response response, Exception e) {
                                super.onError(call, response, e);
                                cancelLoadingDialog();
                                Toast.makeText(SheZhiActivity.this, getResources().getString(R.string.qingqiushibai), Toast.LENGTH_SHORT).show();
                            }
                        });
            } else {
                Toast.makeText(this, "没有数据", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private OkObject getOkObject2() {
        String url = Constant.HOST + Constant.Url.APPUSERSERVICE + "user/modify";
        HttpHeaders headers = new HttpHeaders();
        headers.put(Constant.TOKEN, appLoginResult.getToken());
        HashMap<String, String> params = new HashMap<>();
        return new OkObject(headers, params, url);
    }

    private void BaoCun() {
        AppUserModification appUserModification = new AppUserModification(
                appUser.getUuid(),
                appUser.getCreated(),
                appUser.getModified(),
                appUser.getCreator(),
                appUser.getModifier(),
                appUser.getOrgId(),
                appUser.getMobile(),
                appUser.getName(),
                appUser.getNickname(),
                appUser.getPhoto(),
                appUser.getSex(),
                appUser.getAge(),
                appUser.getBirthday(),
                appUser.getAddress(),
                appUser.getRemark()
        );
        LogUtil.LogShitou("SheZhiActivity--个人信息修改对象", GsonUtils.parseObject(appUserModification));
        showLoadingDialog();
        OkObject okObject = getOkObject2();
        OkGo.post(okObject.getUrl())//
                .tag(this)//
                .headers(okObject.getHeaders())
                .upJson(GsonUtils.parseObject(appUserModification))//
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        cancelLoadingDialog();
                        LogUtil.LogShitou("SheZhiActivity--个人信息修改返回", ""+s);
                        try {
                            NormalBack normalBack = GsonUtils.parseJSON(s, NormalBack.class);
                            if (normalBack.isSuccess()){
                                adapter.notifyDataSetChanged();
                                Toast.makeText(SheZhiActivity.this, "修改成功", Toast.LENGTH_SHORT).show();
                            }else {
                                Toast.makeText(SheZhiActivity.this, normalBack.getMessage(), Toast.LENGTH_SHORT).show();
                            }
                        } catch (Exception e) {
                            Toast.makeText(SheZhiActivity.this, getResources().getString(R.string.shujuchucuo), Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                        cancelLoadingDialog();
                        if (response != null) {
                            if (response.code() == 401) {
                                showReLoginDialog();
                            }
                        }
                        Toast.makeText(SheZhiActivity.this, getResources().getString(R.string.qingqiushibai), Toast.LENGTH_SHORT).show();
                    }
                });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.imageBack:
                finish();
                break;
        }
    }
}